package cn.xunjie.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头获取U-TOKEN
        String token = request.getHeader("U-TOKEN");
        //2获取redis数据
        Object logTmp = redisTemplate.opsForValue().get(token);
        //3.如果token不为空就
        if(StringUtils.isEmpty(logTmp)){
            redisTemplate.opsForValue().set(
                    token,
                    logTmp,
                    30,
                    TimeUnit.MINUTES
            );
            return true;
        }
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();

        return false;
    }
}
